
// 将服务器返回的数据格式化为tree接受的格式  listToTree(data, options) 
export function listToTree ( data, options ) {
    if (data === undefined ) return ; 
    options = options || {};
    let ID_KEY = options.idKey || 'id';
    let PARENT_KEY = options.parentKey || 'parent_id';
    let CHILDREN_KEY = options.childrenKey || 'children';
    let TREE_NODE_KEY = 'key' ;
    
    var tree = {},
        childrenOf = {};
    let item, id, parent_id;
    for (var i = 0, length = data.length; i < length; i++) {
        item = data[i];
        id = item[ID_KEY];
        //init tree node key ,normaly , key will equal to id 
        item[TREE_NODE_KEY] = id ; 
        parent_id = item[PARENT_KEY] || 0;
        // every item may have children
        childrenOf[id] = childrenOf[id] || {};
        // init its children
        item[CHILDREN_KEY] = childrenOf[id];
        if (parent_id !== 0) {
            // init its parent's children object
            childrenOf[parent_id] = childrenOf[parent_id] || {};
            // push it into its parent's children object
            childrenOf[parent_id][item.id] = item;
        } else {
            tree[item.id] = item;
        }
    };
    return tree;
}